package com.jh.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jh.constant.EmployeeConstant;
import com.jh.constant.MessageConstant;
import com.jh.constant.StatusConstant;
import com.jh.dto.*;
import com.jh.entity.Employee;
import com.jh.exception.AccountLockedException;
import com.jh.exception.AccountNotFoundException;
import com.jh.exception.PasswordEditFailedException;
import com.jh.exception.PasswordErrorException;
import com.jh.mapper.EmployeeMapper;
import com.jh.result.PageResult;
import com.jh.service.EmployeeService;
import com.jh.utils.EmployeeUtil;
import com.jh.vo.EmployeeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.List;


@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String phone = employeeLoginDTO.getPhone();
        String password = employeeLoginDTO.getPassword();

        //1、根据电话号码查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(phone);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new PasswordErrorException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传过来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 密码修改
     * @param passwordEditDTO
     * @return
     */
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        String oldPassword = passwordEditDTO.getOldPassword();
        String rightPassword=employeeMapper.getbyEmpId(passwordEditDTO);
        if(rightPassword==null||rightPassword==""){
            //新密码为空，抛出异常
            throw new PasswordEditFailedException(MessageConstant.NEW_PASSWORD_NOT_EXIST);
        }
        //对前端传过来的明文密码进行md5加密处理
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if(!rightPassword.equals(oldPassword)){
            //原密码错误，抛出异常
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_ERROR);
        }
//        修改密码，执行数据库操作
        passwordEditDTO.setNewPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        employeeMapper.updatePassword(passwordEditDTO);
    }

    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO
     */
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        employeePageQueryDTO.setPageSize(10);
        // 创建 MyBatis-Plus 的 Page 对象
        Page<EmployeeVO> page = new Page<>(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        //执行查询
        page=employeeMapper.page(page,employeePageQueryDTO);
        long total = page.getTotal();
        List<EmployeeVO> records = page.getRecords();
        return new PageResult(total,records);
    }

    /**
     * 员工修改
     *
     * @param employeeDTO 包含要更新的员工信息的DTO对象
     */
    public void edit(EmployeeDTO employeeDTO) {
        Employee employee = EmployeeUtil.convertToEmployee(employeeDTO);//对员工字段和职位字段进行数据转换，并且数据迁移
        // 现在employee对象的职位字段已经正确设置，可以执行更新操作
        employeeMapper.update(employee);
    }

    /**
     * 员工删除
     * @param id
     */
    public void delete(Long id) {
        employeeMapper.delete(id);
    }

    /**
     * 员工新增
     *
     * @param employeeDTO
     * @return
     */
    public String save(EmployeeDTO employeeDTO) {
        // 使用身份证号查询数据库中是否已存在该员工
        String idCard = employeeDTO.getIdCard();
        Employee existingEmployee = employeeMapper.findByIdCard(idCard);

        if (existingEmployee != null) {
            // 如果存在相同身份证号的员工，返回错误信息
            return EmployeeConstant.EMPLOYEE_ALREADY_EXISTS;
        } else {
            // 如果不存在，则创建新员工并保存
            Employee employee = EmployeeUtil.convertToEmployee(employeeDTO);//数据转换，员工字段和职位字段
            employee.setPassword("e10adc3949ba59abbe56e057f20f883e");
            employee.setStatus(1);
            employeeMapper.add(employee);
            return EmployeeConstant.EMPLOYEE_ADDED_SUCCESSFULLY;
        }
    }
}
